//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

/* Timer driver in emulator.
 * Ver. 1.0 , By Leng Bo, 2005-3-2
 */

#include <windows.h>
#include <mmsystem.h>
#include <stdio.h>
#include <assert.h>

#define TARGET_RESOLUTION 1         // 1-millisecond target resolution

TIMECAPS g_timeCaps;
UINT     g_wTimerRes;

EXTERN_C void CALLBACK TimerCallback(UINT wTimerID, UINT msg,
    DWORD dwUser, DWORD dw1, DWORD dw2);

EXTERN_C UINT StartTimer(int uDelay)
{
    UINT wTimerID;
    if (timeGetDevCaps(&g_timeCaps, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
        // Error; application can't continue.
        wprintf(L"Create Timer Error!\n");
        return 0;
    }

    g_wTimerRes = min(max(g_timeCaps.wPeriodMin, TARGET_RESOLUTION), g_timeCaps.wPeriodMax);
    timeBeginPeriod(g_wTimerRes);

    wTimerID = timeSetEvent(
        uDelay,                        // delay
        g_wTimerRes,                     // resolution (global variable)
        TimerCallback,                 // callback function
        0,                          // user data
        TIME_PERIODIC );               // periodic timer event
    if (!wTimerID) {
        wprintf(L"Create Timer Error!\n");
        return 0;
    }
    return wTimerID;
}

EXTERN_C void StopTimer(UINT timerId)
{
    timeKillEvent(timerId);
    timeEndPeriod(g_wTimerRes);
}

EXTERN_C UINT _StartTimer(UINT uSeconds, void * pTimerProc, UINT uType)
{
    UINT wTimerID;
    wTimerID = timeSetEvent(
        uSeconds*1000,      // delay
        0,                  //default accuracy
        (LPTIMECALLBACK)pTimerProc,      // callback function
        0,                  // user data
        TIME_ONESHOT );            // onshot or periodic timer event

    if (!wTimerID) {
        wprintf(L"_StartTimer Error!\n");
        return 0;
    }
    else {
        //printf("_StartTimer\n");
    }
    return wTimerID;
}

EXTERN_C void _StopTimer(UINT wTimerID)
{
    timeKillEvent(wTimerID);
    //printf("_StopTimer\n");
}
